<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="请输入mac地址信息" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" clearable/>
      <!--      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">-->
      <!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      <!--      </el-select>-->
      <el-select v-model="listQuery.type" placeholder="设备类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <!--      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">-->
      <!--        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />-->
      <!--      </el-select>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="$router.push('/keep/index')">
        新增
      </el-button>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">-->
      <!--        Export-->
      <!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        reviewer-->
      <!--      </el-checkbox>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <!--      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.id+1 }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="设备名称" width="250px" align="center">
        <template slot-scope="{row}">
         <span class="link-type" @click="handleUpdate(row)"> {{ row.device_type | typeFilter }}
          <span>{{ row.id }}</span>
           </span>
        </template>
      </el-table-column>
      <el-table-column label="设备mac地址" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.device_mac }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="所属区域" width="250px" align="center">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.person }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="设备所属" width="250px" align="center">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.phone }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="合作银行" width="110px" align="center">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.bank | bankFilter }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span style="color:red;">{{ row.reviewer }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="Imp" width="80px">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="Readings" align="center" width="95">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span v-if="row.pageviews" class="link-type" @click="handleFetchPv(row.pageviews)">{{ row.pageviews }}</span>-->
      <!--          <span v-else>0</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="状态" class-name="status-col" width="100">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <el-tag :type="row.status | statusFilter">-->
      <!--            {{ row.status | stateFilter }}-->
      <!--          </el-tag>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">

          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            查看
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdateimage(row)">
            上传图片
          </el-button>
          <!--          <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">-->
          <!--            Publish-->
          <!--          </el-button>-->
          <!--          <el-button v-if="row.status!='draft'" size="mini" @click="handleModifyStatus(row,'draft')">-->
          <!--            Draft-->
          <!--          </el-button>-->
<!--          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">-->
<!--            删除-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm"  :model="temp" label-position="left" label-width="100px" style="width: 600px; margin-left:150px;">
        <el-form-item label="设备类型" prop="title">
          <el-input :value="temp.device_type | typeFilter" />
        </el-form-item>
        <el-form-item label="设备编号" prop="num">
          <el-input :value="temp.device_mac" />
        </el-form-item>
        <el-form-item label="维保前图片信息" prop="timestamp">
          <el-image
            style="width: 100px; height: 100px"
            :src="url_per"
            :preview-src-list="srcList_per"
          />
        </el-form-item>
        <el-form-item label="维保后图片信息" prop="timestamp">
          <el-image
            style="width: 100px; height: 100px"
            :src="url_end"
            :preview-src-list="srcList_end"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.device_desc"  :disabled="true" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData('dataForm')">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible_img">
      <el-form ref="imageForm"  :model="temp" label-position="left" label-width="100px" style="width: 600px; margin-left:150px;">
        <el-form-item label="设备mac" prop="device_mac">
          <el-input :value="temp.device_mac" />
        </el-form-item>
        <el-form-item label="上传维保后信息" prop="image">
          <el-upload
            ref="upload"
            class="upload-demo"
            multiple
            action="http://8.141.50.32/admin/subject/uploadfile"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <!--        <el-form-item label="Imp">-->
        <!--          <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />-->
        <!--        </el-form-item>-->
        <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible_img = false">
          返回
        </el-button>
        <el-button type="primary" @click="sbmitimgData_Keep('imageForm')">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { fetchPv, createArticle, updateArticle } from '@/api/article'
  import waves from '@/directive/waves' // waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import { GetListKeep, upimage_keep} from '@/api/device'

  import { scrollTo } from '@/utils/scroll-to'
  import elementIcons from '@/views/icons/element-icons'
  import { getKeepImageList } from '@/api/device'

  // 设备类型信息
  const calendarTypeOptions = [
    { key: '0', display_name: '注册机' },
    { key: '1', display_name: '考勤机' },
    { key: '2', display_name: '4G平板考勤机' },
    { key: '3', display_name: '测温平板' },
    { key: '4', display_name: '平板' },
    { key: '5', display_name: '海思平板' },
    { key: '6', display_name: '老版平板' },
    { key: '8', display_name: '路由器' },
    { key: '7', display_name: '数据卡' },
    { key: '9', display_name: '其他' }
  ]
  // 状态信息
  const calendarStateOptions = [
    { key: '0', display_name: '停工' },
    { key: '1', display_name: '开工' },
    { key: '2', display_name: '完工' },
    { key: '3', display_name: '筹建' },
    { key: '4', display_name: '立项' }
  ]
  // 合作银行信息
  const calendarBankOptions = [
    { key: '0', display_name: '农商银行' },
    { key: '1', display_name: '邮储银行' },
    { key: '2', display_name: '工商银行' },
    { key: '3', display_name: '恒丰银行' },
    { key: '4', display_name: '兴业银行' },
    { key: '5', display_name: '中国银行' },
    { key: '6', display_name: '东营银行' }
  ]

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})
  // 获取项目的状态信息
  const calendarStateKeyValue = calendarStateOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})
  // 获取合作银行的信息
  const calendarBankKeyValue = calendarBankOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'info',
          0: 'danger',
          3: 'warning',
          4: 'error'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      },
      stateFilter(type) {
        return calendarStateKeyValue[type]
      },
      bankFilter(type) {
        return calendarBankKeyValue[type]
      }
    },
    data() {
      return {

        url_per: 'http://8.141.50.32//upload/20210114/3ac4bab2a6e26696476e343cbbfbfcbb.png',
        srcList_per: [
          'http://8.141.50.32//upload/20210114/3ac4bab2a6e26696476e343cbbfbfcbb.png'
        ],
        url_end: 'http://8.141.50.32//upload/20210114/3ac4bab2a6e26696476e343cbbfbfcbb.png',
        srcList_end: [
          'http://8.141.50.32//upload/20210114/3ac4bab2a6e26696476e343cbbfbfcbb.png'
        ],


        // 文件列表
        fileList: [],
        tableKey: 0,
        list: null,
        image: '',
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        form: {
          device_mac: ''
        },
        // repair_phone:'',
        // repair_person:'',
        // repairtime_end:'',
        // repairtime_start:'',
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        // sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        calendarStateOptions: [],
        showReviewer: false,
        temp: {
          device_mac: '',
          remark: ''
        },
        dialogFormVisible: false,
        dialogFormVisible_img: false,
        dialogStatus: '',
        textMap: {
          update: '修改项目状态',
          create: 'Create'
        },
        dialogPvVisible: false,
        pvData: [],
        DataSelect: [], // 时间
        // rules: {
        //   type: [{ required: true, message: 'type is required', trigger: 'change' }],
        //   timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        //   // title: [{ required: true, message: 'title is required', trigger: 'blur' }],
        //   bank: [{ required: true, message: 'title is required', trigger: 'blur' }],
        //   state: [{ required: true, message: '请选择项目状态', trigger: 'change' }]
        // },
        downloadLoading: false
      }
    },
    created() {
      this.getList()
    },
    methods: {
      // 文件上传
      submitUpload() {
        this.$refs.upload.submit()
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
        this.image = ''
        for (const i in fileList) {
          this.image += fileList[i]['response'] + ';'
        }
      },
      handlePreview(file) {
        console.log(file)
      },
      handleSuccess(response, file, fileList) {
        this.image = ''
        for (const i in fileList) {
          this.image += fileList[i]['response'] + ';'
        }
      },
      getList(val) {
        this.listLoading = true
        if (val != undefined) {
          this.page = val.page,
            this.limit = val.limit
        }
        var type_search = this.listQuery.type
        var title_search = this.listQuery.title
        GetListKeep(
          {
            page: this.page,
            limit: this.limit,
            device_type: type_search,
            device_mac: title_search
          }).then((res) => {
          if (res.code == '20000') {
            this.list = res.data
            // console.log(this.list)
            this.total = res.msg
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)

            // this.$message('提交成功!')
          } else {
            this.$message({
              message: '提交失败，请联系管理员!',
              type: 'error'
            })
          }
        })
      },
      // 上传文件信息到维修表单中
      sbmitimgData_Keep(imageForm) {
        if (this.image.length == 0) {
          this.$notify({
            title: '信息',
            message: '请选择照片后再提交',
            type: 'warning',
            duration: 2000
          })
          return false
        }
        this.$refs['imageForm'].validate((valid) => {
          const tempData = Object.assign({}, this.temp)
          // 获取上传的文件列表
          if (valid) {
            upimage_keep(
              {
                device_image_end: this.image,
                device_mac: tempData.device_mac,
                subject_remark: tempData.remark
              }).then((res) => {
              if (res.code == '20000') {
                // console.log(this.list)
                setTimeout(() => {
                  this.listLoading = false
                }, 1.5 * 1000)
                if (res.data == 0) {
                  this.$notify({
                    title: '信息',
                    message: '数据相同，无需重复提交',
                    type: 'warning',
                    duration: 2000
                  })
                } else {
                  this.$notify({
                    title: '信息',
                    message: '提交成功',
                    type: 'success',
                    duration: 2000
                  })
                  console.log('b')
                  this.dialogFormVisible_img = false
                  console.log('e')
                }
              } else {
                this.$message({
                  message: '提交失败，请联系管理员!',
                  type: 'error'
                })
              }
            }).catch(err => {
              console.log('err', err)
            })
          }
        })
      },

      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: '',
          type: '',
          id_s: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            createArticle(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        console.log(this.temp)
        getKeepImageList(
          {
            device_mac: this.temp.device_mac
          }).then((res) => {
          if (res.code == '20000') {
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)


            this.url_per = res.data.url
            this.srcList_per = res.data.list
            this.url_end = res.msg.url
            this.srcList_end = res.msg.list
          } else {
            this.$message({
              message: '提交失败，请联系管理员!',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log('err', err)
        })
      },
      handleUpdateimage(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible_img = true
        this.$nextTick(() => {
          this.$refs['imageForm'].clearValidate()
        })
      },
      updateData(dataForm) {
        this.$refs['dataForm'].validate((valid) => {
          const tempData = Object.assign({}, this.temp)
          console.log(tempData)
          if (valid) {
            if (this.form.person == '') {
              var person = undefined
              var phone = undefined
            } else {
              var person = this.form.person
              var phone = this.form.phone
            }
            if (this.DataSelect == '') {
              var repair_time_end = undefined
              var repair_time_start = undefined
            } else {
              var repair_time_start = this.DataSelect[0]
              var repair_time_end = this.DataSelect[1]
            }
            UpdateRepair(
              {
                subject_num: tempData.num,
                id: tempData.id_s,
                repair_person: person,
                repair_phone: phone,
                repairtime_end: repair_time_end,
                repairtime_start: repair_time_start
              }).then((res) => {
              if (res.code == '20000') {
                // console.log(this.list)
                setTimeout(() => {
                  this.listLoading = false
                }, 1.5 * 1000)

                //  this.$message('修改成功!')
                if (res.data == 0) {
                  this.$notify({
                    title: '信息',
                    message: '数据相同，无需重复提交',
                    type: 'warning'
                  })
                } else {
                  this.$notify({
                    title: '信息',
                    message: '提交成功',
                    type: 'success'
                  })
                  this.dialogFormVisible = false
                }
              } else {
                this.$message({
                  message: '提交失败，请联系管理员!',
                  type: 'error'
                })
              }
            })
          }
        })
      },
      handleDelete(row, index) {
        console.log(row.num, index)
        DelSubject(
          {
            subject_num: row.num
          }).then((res) => {
          if (res.code == '20000') {
            // console.log(this.list)
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)

            //  this.$message('修改成功!')
            if (res.data == 0) {
              this.$notify({
                title: '信息',
                message: '已删除，无需重复操作',
                type: 'warning',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '信息',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            }
          } else {
            this.$message({
              message: '删除失败，请联系管理员史岩松!',
              type: 'error'
            })
          }
        })
        this.list.splice(index, 1)
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
</script>
